package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;



@Api("文件上传")
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {

    @Value("${image.url}")
    private String imagerUrl;

    @ApiOperation("上传图片")
    @PostMapping("/fileUpload")
    private Result fileUpload(MultipartFile file) throws IOException, MyException {
        //配置跟踪器的ip以及端口
        String path = ClassUtils.getDefaultClassLoader()
                .getResource("fdfs_client.conf").getPath();
        ClientGlobal.init(path);

        //1.创建TrackerClient 客户端
        TrackerClient trackerClient = new TrackerClient();
        //2.连接TrackerServer端
        TrackerServer trackerServer = trackerClient.getConnection();

        //3.创建Storage的客户端
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,storageServer);
        //4.上传文件

        //获取文件后缀名称
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());

        String fileId = storageClient1.upload_file1(file.getBytes(), extension, null);
        System.out.println(imagerUrl+fileId);
        return Result.ok(imagerUrl+fileId);
    }

}
